﻿Imports System.IO

Public Class ExploradorEscandallos
    Inherits System.Web.UI.Page

    Const COL_ICONO = 0
    Const COL_AR_REF = 1
    Const COL_DESCRIPCION = 2
    Const COL_MEDIDAS = 3
    Const COL_CANTIDAD = 4
    Const COL_STOCK = 5
    Const COL_FABRICABLE = 6
    Const COL_NECESIDAD_TOTAL = 7
    Const COL_NECESIDAD_FABRICACION = 8
    Const COL_PF = 9
    Const COL_BOTONVER = 10
    Const COL_NIVEL = 11
    Const COL_PADRE = 12
    Const COL_OMITIRENSIMULACION = 13
    Const COL_BTNCAD = 14

    'Public TProductosSinStock As DSTablasAuxiliares.ProductosSinStockDataTable
    'Public VProductosSinStock As DataView

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim Script As ClientScriptManager = Page.ClientScript
        Script.RegisterClientScriptBlock(GetType(String), "ExploradorEscandallos", File.ReadAllText(Server.MapPath("~/Scripts/ExploradorEscandallos.js")))

    End Sub

    Private Sub CargarListaEscandallos(ByVal GrupoEscandallos As String)
        Dim SQL As String = "SELECT F_ARTICLE.AR_REF, F_ARTICLE.AR_DESIGN, AS_QteSto " _
            & " FROM F_ARTICLE F_ARTICLE " _
            & " LEFT JOIN F_ARTSTOCK ON F_ARTICLE.AR_REF = F_ARTSTOCK.AR_Ref " _
            & " WHERE (F_ARTICLE.AR_CODEFISCAL LIKE '" & GrupoEscandallos & "%') AND (F_ARTICLE.AR_NOMENCL=1) " _
            & " ORDER BY F_ARTICLE.AR_DESIGN "

        Dim BD As New clsBD
        BD.ConectarSAGE(My.Settings.DSNFacody)
        Dim TablaEscandallos As DataTable = BD.cargaTablaSAGE(SQL)
        BD.CerrarSAGE()
        GVEscandallos.DataSource = TablaEscandallos
        GVEscandallos.DataBind()

        GVEscandallos.CssClass = "tabla"
        GVEscandallos.AlternatingRowStyle.CssClass = "filatablaalt"
        GVEscandallos.EmptyDataText = "No hay resultados que mostrar"
        If GVEscandallos.HeaderRow IsNot Nothing Then
            GVEscandallos.HeaderRow.CssClass = "encabezadotabla"
        End If

    End Sub

    Sub btnEscandallos_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEscandallos.Click
        pnlEscandallos.Visible = True
        pnlDetalle.Visible = False
        pnlFabricacion.Visible = False
    End Sub

    Protected Sub btnComponentes_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnComponentes.Click
        pnlEscandallos.Visible = False
        pnlDetalle.Visible = True
        GenerarIDsFilasComponentes()
    End Sub

    Private Sub GVEscandallos_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GVEscandallos.RowCommand
        Select Case e.CommandName
            Case "ver"
                LblNombreEscandallo.Text = GVEscandallos.Rows(CInt(e.CommandArgument)).Cells(2).Text
                CargarGridComponentes(GVEscandallos.Rows(CInt(e.CommandArgument)).Cells(1).Text, ConvertirDec(GVEscandallos.Rows(CInt(e.CommandArgument)).Cells(3).Text), False)

                pnlEscandallos.Visible = False
                pnlDetalle.Visible = True
            Case "autocad"
                Dim RutaArchivoCAD As String = My.Settings.RutaAutocad & GVEscandallos.Rows(CInt(e.CommandArgument)).Cells(1).Text & ".dxf"
                If File.Exists(RutaArchivoCAD) Then
                    Response.Redirect(RutaArchivoCAD)
                End If
        End Select

    End Sub

    Function IconoImagen(ByVal CodArticulo As String) As String
        If File.Exists(Server.MapPath("imgproductos/peq/" & CodArticulo & ".jpg")) Then
            Return "~/imgproductos/peq/" & CodArticulo & ".jpg"
        Else
            Return "~/img/blanco.png"
        End If
    End Function

    Public Sub CargarGridComponentes(ByVal CodEscandallo As String, ByVal StockEscandallo As Decimal, ByVal MostrarFabricacion As Boolean)

        Dim TablaResultado As DataTable = Nothing
        Dim Fabricacion As Decimal = 0
        Fabricacion = CargarComponentes(CodEscandallo, TablaResultado, 1)

        'Insertar fila de escandallo principal
        Dim FilaPrincipal As DataRow = TablaResultado.NewRow
        FilaPrincipal("AR_REF") = CodEscandallo
        FilaPrincipal("AR_DESIGN") = LblNombreEscandallo.Text
        FilaPrincipal("NO_Qte") = 1
        FilaPrincipal("AS_QteSto") = StockEscandallo
        FilaPrincipal("Fabricable") = Fabricacion
        FilaPrincipal("Nivel") = 0
        TablaResultado.Rows.InsertAt(FilaPrincipal, 0)

        GVComponentes.DataSource = TablaResultado
        GVComponentes.DataBind()
        GVComponentes.CssClass = "tablap"
        'GVComponentes.AlternatingRowStyle.CssClass = "filatablaalt"
        GVComponentes.HeaderRow.CssClass = "encabezadotabla"

        Dim Fila As GridViewRow
        For Each Fila In GVComponentes.Rows
            If Fila.Cells(COL_NIVEL).Text <> "" Then
                If CInt(Fila.Cells(COL_NIVEL).Text) > 1 Then
                    'Fila.Visible = False
                    Fila.Style.Add("display", "none")
                End If
                Fila.ClientIDMode = UI.ClientIDMode.Static
                Fila.ID = GenerarIDClienteFila(Fila)

                If Fila.Cells(COL_AR_REF).Text = "&nbsp;" Then
                    Fila.Cells(COL_AR_REF).Text = ""
                    Fila.Cells(COL_CANTIDAD).Text = ""
                    Fila.Cells(COL_FABRICABLE).Text = ""
                    Fila.Cells(COL_STOCK).Text = ""
                    Fila.Cells(COL_NECESIDAD_FABRICACION).Text = ""
                    Fila.Cells(COL_FABRICABLE).Text = ""
                    Fila.Cells(COL_ICONO).Controls.Clear()
                    Fila.Cells(COL_BTNCAD).Controls.Clear()
                    Fila.Cells(COL_BOTONVER).Controls.Clear()
                Else
                    Fila.Cells(COL_DESCRIPCION).Style.Add("padding-left", (CInt(Fila.Cells(COL_NIVEL).Text)) * 20 & "px")
                    Fila.Cells(COL_DESCRIPCION).Style.Add("background-image", "url('img/sep.png')")
                    Fila.Cells(COL_DESCRIPCION).Style.Add("background-repeat", "repeat-y")
                    Fila.Cells(COL_DESCRIPCION).Style.Add("background-position", (CInt(Fila.Cells(COL_NIVEL).Text) - 1) * 20 & "px")

                    Dim btnVer As Image = Fila.Cells(COL_BOTONVER).Controls(1)
                    Dim IDsSublineas As ArrayList = SubLineas(Fila)
                    Dim ID As String, Script As String = ""
                    For Each ID In IDsSublineas
                        Script &= "mostrarOcultar('" & ID & "'); "
                    Next
                    If Script <> "" And CInt(Fila.Cells(COL_NIVEL).Text) > 0 Then
                        btnVer.Attributes.Add("onclick", Script)
                    Else
                        btnVer.Visible = False
                    End If
                End If

            End If
        Next

        If Not MostrarFabricacion Then
            GVComponentes.Columns(COL_NECESIDAD_TOTAL).Visible = False
            GVComponentes.Columns(COL_NECESIDAD_FABRICACION).Visible = False
            GVComponentes.Columns(COL_PF).Visible = False
        End If

    End Sub

    Private Function SubLineas(ByVal Fila As GridViewRow) As ArrayList
        Dim Resultado As New ArrayList

        Dim IFila As Integer = Fila.RowIndex + 1
        Do While IFila < GVComponentes.Rows.Count _
                        AndAlso CInt(GVComponentes.Rows(IFila).Cells(COL_NIVEL).Text) > _
                        CInt(Fila.Cells(COL_NIVEL).Text)
            If (GVComponentes.Rows(IFila).Cells(COL_NIVEL).Text) = _
                            CInt(Fila.Cells(COL_NIVEL).Text) + 1 Then
                Resultado.Add(GenerarIDClienteFila(GVComponentes.Rows(IFila)))
            End If
            IFila += 1
        Loop

        Return Resultado
    End Function

    Private Function GenerarIDClienteFila(ByVal Fila As GridViewRow) As String
        Dim ID As String
        ID = Fila.Cells(COL_PADRE).Text & "_" & Fila.Cells(COL_AR_REF).Text
        Return ID
    End Function

    Public Function CargarComponentes(ByVal CodEscandallo As String, ByRef TablaResultado As DataTable, ByVal NivelRecursivo As Integer) As Decimal

        Dim TablaComponentes As DataTable = LeerTablaComponentes(CodEscandallo, NivelRecursivo)
        Dim Fabricable As Decimal = -1
        If TablaResultado Is Nothing Then
            TablaResultado = TablaComponentes.Clone
        End If

        Dim Fila As DataRow
        Dim NuevaFila As DataRow
        For Each Fila In TablaComponentes.Rows
            TablaResultado.ImportRow(Fila)
            NuevaFila = TablaResultado.Rows(TablaResultado.Rows.Count - 1)

            NuevaFila("Fabricable") = CargarComponentes(Fila("AR_REF"), TablaResultado, NivelRecursivo + 1)

            Dim Stock As Decimal
            If NuevaFila("AS_QteSto") Is DBNull.Value Then
                Stock = 0
            Else
                Stock = NuevaFila("AS_QteSto")
            End If

            'Dim SinStock As Integer = VProductosSinStock.Find(Fila("AR_REF"))
            'If SinStock < 0 Then
            If Fila("OMITIRENSIMULACION") Is DBNull.Value OrElse Fila("OMITIRENSIMULACION").trim = "" Then
                If Fila("NO_Qte") = 0 Then
                    Fabricable = Stock + NuevaFila("Fabricable")
                Else
                    Dim TempFabricable As Decimal = (Stock + NuevaFila("Fabricable")) / Fila("NO_Qte")
                    If Fabricable < 0 Or TempFabricable < Fabricable Then
                        Fabricable = TempFabricable
                    End If
                End If
            End If

            If NivelRecursivo = 1 Then
                Dim FilaVacia As DataRow = TablaResultado.NewRow
                FilaVacia = TablaResultado.NewRow
                FilaVacia("AR_REF") = ""
                FilaVacia("AR_DESIGN") = ""
                FilaVacia("NO_Qte") = 0
                FilaVacia("AS_QteSto") = 0
                FilaVacia("Fabricable") = 0
                FilaVacia("Nivel") = 1
                TablaResultado.Rows.Add(FilaVacia)
            End If

        Next
        TablaComponentes = Nothing

        If Fabricable = -1 Then
            Fabricable = 0
        End If

        Return Fabricable
    End Function

    Private Function LeerTablaComponentes(ByVal CodArticulo As String, ByVal NivelRecursivo As Integer) As DataTable
        Dim SQL As String
        SQL = "SELECT F_NOMENCLAT.AR_REF AS PADRE, F_ARTICLE.AR_REF, F_ARTICLE.AR_DESIGN, F_ARTICLE.MEDIDAS, F_ARTICLE.OMITIRENSIMULACION,NO_Qte, AS_QteSto, " _
            & NivelRecursivo & " AS Nivel, 0 as Fabricable " _
            & " FROM F_NOMENCLAT " _
            & " LEFT JOIN F_ARTICLE ON F_NOMENCLAT.NO_RefDet = F_ARTICLE.AR_REF " _
            & " LEFT JOIN F_ARTSTOCK ON F_NOMENCLAT.NO_RefDet = F_ARTSTOCK.AR_Ref " _
            & " WHERE F_NOMENCLAT.AR_REF = '" & CodArticulo & "'" _
            & " AND (F_ARTSTOCK.DE_No = 1 OR F_ARTSTOCK.DE_No IS NULL) " _
            & " ORDER BY F_ARTICLE.AR_REF "
        '& " ORDER BY NO_ORDRE "
        Dim BD As New clsBD
        BD.ConectarSAGE(My.Settings.DSNFacody)
        Dim TablaComponentes As DataTable = BD.cargaTablaSAGE(SQL)
        BD.CerrarSAGE()
        Return TablaComponentes
    End Function

    Private Sub GVComponentes_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVComponentes.RowDataBound
        e.Row.Cells(COL_PADRE).Visible = False
        e.Row.Cells(COL_NIVEL).Visible = False
        e.Row.Cells(COL_OMITIRENSIMULACION).Visible = False

        'Dim myCell As TableCell
        'For Each myCell In e.Row.Cells
        '    myCell.CssClass = "celdafija"
        '    myCell.Wrap = False
        'Next
    End Sub

    Protected Sub TVEscandallos_SelectedNodeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TVEscandallos.SelectedNodeChanged
        CargarListaEscandallos(TVEscandallos.SelectedValue)
    End Sub

    Protected Sub Simulacion_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Simulacion.Click
        pnlFabricacion.Visible = Not pnlFabricacion.Visible
        GenerarIDsFilasComponentes()
    End Sub

    Protected Sub btnFabricar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFabricar.Click
        Dim LineaCaldera As GridViewRow
        If GVComponentes.Rows.Count > 0 Then
            LineaCaldera = GVComponentes.Rows(0)
            LineaCaldera.Cells(COL_NECESIDAD_TOTAL).Text = txtCantidadFabricar.Text
            LineaCaldera.Cells(COL_NECESIDAD_FABRICACION).Text = txtCantidadFabricar.Text
            GVComponentes.Columns(COL_NECESIDAD_TOTAL).Visible = True
            GVComponentes.Columns(COL_NECESIDAD_FABRICACION).Visible = True
            GVComponentes.Columns(COL_PF).Visible = True
            GVComponentes.Columns(COL_BTNCAD).Visible = False
            GVComponentes.Columns(COL_ICONO).Visible = False
            'GVComponentes.RowStyle.Wrap = False
            'GVComponentes.Columns(COL_AR_REF).ItemStyle.Width = New Unit(20)
            SimularFabricacion(0)
            GenerarIDsFilasComponentes()
        End If
    End Sub

    Private Sub SimularFabricacion(ByVal ILineaPadre As Integer)

        Dim FilaPadre As GridViewRow = GVComponentes.Rows(ILineaPadre)
        Dim NecesidadPadre As Decimal = CDec(FilaPadre.Cells(COL_NECESIDAD_FABRICACION).Text)
        Dim NivelPadre As Integer = CInt(FilaPadre.Cells(COL_NIVEL).Text)
        'Recorrer subcomponentes
        Dim IFila As Integer = ILineaPadre + 1
        Dim FilaComponente As GridViewRow
        Do While IFila < GVComponentes.Rows.Count
            FilaComponente = GVComponentes.Rows(IFila)

            If FilaComponente.Cells(COL_AR_REF).Text <> "" Then
                Select Case CInt(FilaComponente.Cells(COL_NIVEL).Text)
                    Case NivelPadre
                        Exit Do
                    Case NivelPadre + 1
                        'Calcular simulación
                        Dim Necesidad As Decimal = NecesidadPadre * CDec(FilaComponente.Cells(COL_CANTIDAD).Text)
                        FilaComponente.Cells(COL_NECESIDAD_TOTAL).Text = Necesidad
                        If Necesidad <= ConvertirDec(FilaComponente.Cells(COL_STOCK).Text) Then
                            FilaComponente.Cells(COL_NECESIDAD_FABRICACION).Text = 0
                            FilaComponente.Cells(COL_PF).Text = ""
                            'FilaComponente.Cells(COL_NECESIDAD_FABRICACION).BackColor = Drawing.Color.Lavender
                        Else
                            Dim CantidadAFabricar As Decimal = Necesidad - ConvertirDec(FilaComponente.Cells(COL_STOCK).Text)
                            FilaComponente.Cells(COL_NECESIDAD_FABRICACION).Text = CantidadAFabricar
                            FilaComponente.Cells(COL_PF).Text = "PF"
                        End If
                        'Procesar sublíneas
                        SimularFabricacion(IFila)
                End Select
            Else
                FilaComponente.Cells(COL_BOTONVER).Controls.Clear()
            End If
            IFila += 1
        Loop

    End Sub

    Private Function ConvertirDec(ByVal Valor As String) As Decimal
        If IsNumeric(Valor) Then
            Return CDec(Valor)
        Else
            Return 0
        End If
    End Function

    Private Sub GenerarIDsFilasComponentes()
        For Each Fila In GVComponentes.Rows
            If Fila.Cells(COL_NIVEL).Text <> "" Then
                Fila.ClientIDMode = UI.ClientIDMode.Static
                Fila.ID = GenerarIDClienteFila(Fila)
            End If
        Next
    End Sub
End Class